package com.wtp.wallpaper.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wtp.wallpaper.common.context.BaseContext;
import com.wtp.wallpaper.mapper.CollectMapper;
import com.wtp.wallpaper.pojo.entity.Collect;
import com.wtp.wallpaper.service.CollectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class CollectionServiceImpl extends ServiceImpl<CollectMapper, Collect> implements CollectService {
    @Override
    public int getListCountByUserId(Long id) {
        return Math.toIntExact(getCollectListByUserId(id).size());
    }

    @Override
    public List<Long> getPictureIdsByUserId(Long currentId) {
        // 使用 lambdaQuery 查询所有与 userId 匹配的 Collect 数据

        return lambdaQuery()
                .eq(Collect::getUserId, currentId)
                .orderByDesc(Collect::getId) //根据时间降序
                .list()  // 获取查询结果的集合
                .stream()  // 转换为 Stream
                .map(Collect::getPicId)  // 提取 pictureId
                .toList();  // 收集为 List<Long>
    }

    @Override
    public List<Collect> getCollectListByUserId(Long id) {
        return lambdaQuery().eq(Collect::getUserId,id).list();
    }

    @Override
    public void changeCollect(Long picId, boolean state) {
        Long userId = Long.valueOf(BaseContext.getCurrentId());
        Collect one = lambdaQuery()
                .eq(Collect::getUserId, userId)
                .eq(Collect::getPicId, picId).one();
        if(state){
            if(one == null){
                Collect collect = Collect.builder()
                        .picId(picId)
                        .userId(userId).build();
                save(collect);
            }
        }else{
            if(one != null){
                baseMapper.deleteById(one.getId());
            }
        }
    }
}
